<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\Comment;
use Hyperf\Context\Context;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PostMapping;

#[Controller]
class CommentController extends AbstractController
{
    #[GetMapping(path: '/api/comment/list')]
    public function list()
    {
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $articleId = $this->request->input('articleId', 10);
        $pId = Comment::query()->where('article_id', $articleId)
            ->with(['user','replyUser'])
            ->whereNull('parent_id')
            ->forPage($pageNum, $pageSize)
            ->pluck('id');

        $list = Comment::query()->select('id', 'article_id', 'user_id', 'user_id as userId', 'reply_user_id', 'parent_id', 'parent_id as parentId', 'content', 'like_count', 'is_stick as isStick', 'ip', 'browser', 'system', 'ip_source as ipSource', 'create_time as createTime')
            ->whereIn('id', $pId)
            ->orWhereIn('parent_id', $pId)
            ->with(['user','replyUser'])
            ->get();

        $comments = $list->toArray();
        $commentMap = [];
        foreach ($comments as $index => $comment) {
            // $comments[$index]['avatar'] = $comment['user']['avatar'];
            // $comments[$index]['nickname'] = $comment['user']['nickname'];
            // unset($comments[$index]['user']); // 可选：移除整个 user 对象
            // $commentMap[$comment['id']] = $comments[$index];

            $comments[$index]['avatar'] = $comment['user']['avatar'];
            $comments[$index]['nickname'] = $comment['user']['nickname'];
            unset($comments[$index]['user']); // 可选：移除整个 user 对象

            $comments[$index]['replyNickname'] = $comment['reply_user']['nickname'] ?? '';
            unset($comments[$index]['reply_user']); // 可选：移除整个 replyUser 对象
            $commentMap[$comment['id']] = $comments[$index];
            // if ($comment['parentId'] !== null){
            //     $commentMap[$comment['parentId']]['children'][] = $commentMap[$comment['id']];
            // }
        }

        // 构建树结构
        $tree = [];
        foreach ($comments as $comment) {
            if ($comment['parentId'] === null || ! isset($commentMap[$comment['parentId']])) {
                // 如果没有 parent_id 或者 parent_id 不存在，则作为根评论
                $tree[] = &$commentMap[$comment['id']];
            } else {
                $commentMap[$comment['parentId']]['children'][] = &$commentMap[$comment['id']];
            }
        }

        // 返回树结构的评论
        $data['searchCount'] = true;
        $data['current'] = (int) $pageNum;
        $data['size'] = (int) $pageSize;
        $data['total'] = Comment::query()->whereNull('parent_id')->count();
        $data['records'] = $tree;
        return success($data);
    }

    #[Middlewares([AuthMiddleware::class])]
    #[PostMapping(path: '/addComment')]
    public function addComment()
    {
        $article_id = $this->request->input('articleId');
        $content = $this->request->input('content');
        Comment::query()->create([
            'article_id' => $article_id,
            'user_id' => Context::get('uid'),
            'content' => $content,
            'parent_id' => $this->request->input('parentId'),
            'reply_user_id' => $this->request->input('replyUserId'),
        ]);
        return success();

    }
}
